import ports;
import voltestrels;
import user;

queryRelationsPorts is package{
  
  Port_In is p0rt{
    on U on DEFAULT do addUser(U);
    
    Users has type ref relation of user;
    var Users := relation{};
    
--    addUser has type action(user);
    addUser(U) do{
      logMsg(info,"New user: $U");
      extend Users with U;
    };
    
    calcTotal() do
      logMsg(info,"total balance is $(total(all U.balance where U in Users))");
       
    getBalance(N) is anyof B where user{name=N;balance=B} in Users;
  };
  
  total(R) is valof{
    var T := 0;
    for r in R do
      T := T+r;
    valis T;
  };

  P1 is connectPort_Out(Port_In);
  
  main() do {
    notify P1 with user{name="alpha";balance=1} on DEFAULT;
    notify P1 with user{name="beta";balance=2} on DEFAULT;
    notify P1 with user{name="gamma";balance=3} on DEFAULT;
    request P1's addUser to addUser(user{name="delta";balance=4});

    logMsg(info,"$(query P1's Users with Users)");
    assert (query P1's Users with Users) = relation{ user{name="alpha";balance=1};
        user{name="beta";balance=2};
        user{name="gamma";balance=3};
        user{name="delta";balance=4} };
    
    request P1's calcTotal to calcTotal();
  }
}